<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>Hi Shiro ~ - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-07-31 14:23">
      July 31, 2019 pm
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      42
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-初识Shiro"><a href="#学习笔记-初识Shiro" class="headerlink" title="学习笔记 : 初识Shiro ~"></a>学习笔记 : 初识Shiro ~</h2><p><em>简介 : <code>Apache Shiro</code>是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能，对于任何一个应用程序,Shiro都可以提供全面的安全管理服务</em></p>
<p><em>权限管理包括用户<code>身份认证</code>和<code>授权</code>两个部分,简称认证授权</em></p>
<ol>
<li><em>身份认证 : 为判断用户是否为合法用户的过程,最常用的身份认证方式就是系统通过核对用户输入的用户名和口令,将其与系统中存储的该用户信息相对比,继而来判断用户身份是否正确</em></li>
<li><em>授权 : 既访问权限,控制用户访问资源的权限. 主体(<code>subject</code>)进行身份认证后需要分配权限方可访问系统的资源</em></li>
</ol>
<h3 id="架构解析"><a href="#架构解析" class="headerlink" title="架构解析"></a>架构解析</h3><p><em>Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境. Shiro可以帮助我们完成 : 认证、授权、加密、会话管理、与Web集成、缓存等. 其基本功能点及其解析如下所示 :</em></p>
<p><img src="/2019/07/31/Hi-Shiro/Hi-Shiro%5Cshiro-framework-api.png" srcset="/img/loading.gif" alt></p>
<ul>
<li><code>Authentication</code> : 身份认证 / 登录,验证用户是不是拥有相应的身份</li>
<li><code>Authorization</code> : 授权,即权限验证,验证某个已认证的用户是否拥有某个权限. 即判断用户是否能做事情,常见的如 : 验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限</li>
<li><code>Session Manager</code> : 会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中. 会话可以是普通JavaSE环境的,也可以是如Web环境的</li>
<li><code>Cryptography</code> : 加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储</li>
<li><code>Web Support</code> : Web支持,可以非常容易的集成到Web环境中</li>
<li><code>Caching</code> : 缓存,比如用户登录后,其用户信息、拥有的角色 / 权限不必每次去查,这样可以提高效率</li>
<li><code>Concurrency</code> : shiro支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去</li>
<li><code>Testing</code> : 提供测试支持</li>
<li><code>Run As</code> : 允许一个用户假装为另一个用户(在他们允许的情况下)的身份进行访问</li>
<li><code>Remember Me</code> : 记住我,这个是非常常见的功能,即一次登录后,下次不用重复登录了</li>
</ul>
<h4 id="外部结构"><a href="#外部结构" class="headerlink" title="外部结构"></a>外部结构</h4><p><em>外部架构图,即从应用程序角度的来观察如何使用Shiro完成工作 :</em></p>
<p><img src="/2019/07/31/Hi-Shiro/Hi-Shiro%5CShiro-%E5%A4%96%E9%83%A8%E6%9E%B6%E6%9E%84%E5%9B%BE.png" srcset="/img/loading.gif" alt></p>
<p><em>可以看到,应用代码直接交互的对象是<code>Subject</code>,也就是说Shiro的对外API核心就是Subject. 其每个API的含义如下所示 :</em></p>
<ul>
<li><code>Subject</code> : 主体,代表了当前”用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等,即为一个抽象概念. 所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager. 可以把Subject认为是一个门面,SecurityManager才是实际的执行者</li>
<li><code>SecurityManager</code> : 安全管理器,即所有与安全有关的操作都会与SecurityManager交互,且它管理着所有Subject. 可以看出它是Shiro的核心,它负责与后边介绍的其他组件进行交互,如果学习过SpringMVC,你可以把它看成<code>DispatcherServlet</code>前端控制器</li>
<li><code>Realm</code> : 域,Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法,也需要从Realm得到用户相应的角色 / 权限进行验证用户是否能进行操作. 可以把Realm看成 DataSource,即安全数据源</li>
</ul>
<p><em>也就是说,最简单的一个Shiro应用可以基本分为以下两个步骤 :</em></p>
<ol>
<li><em>应用代码通过Subject来进行认证和授权,而Subject又将所有的互交都委托给了SecurityManager</em></li>
<li><em>我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其权限进行判断</em></li>
</ol>
<p><em>从以上也可以看出,Shiro不提供维护用户 / 权限,而是通过Realm让开发人员自己注入</em></p>
<h4 id="内部结构"><a href="#内部结构" class="headerlink" title="内部结构"></a>内部结构</h4><p><em>接下来我们来从Shiro内部来看下Shiro的架构,如下图所示 :</em></p>
<p><img src="/2019/07/31/Hi-Shiro/Hi-Shiro%5CShiro-%E5%86%85%E9%83%A8%E7%BB%93%E6%9E%84%E5%9B%BE.png" srcset="/img/loading.gif" alt></p>
<ul>
<li><code>Subject</code> : 主体,可以看到主体可以是任何可以与应用交互的”用户”</li>
<li><code>SecurityManager</code> : 相当于SpringMVC中的<code>DispatcherServlet</code>或Struts2中的FilterDispatcher; 是Shiro的心脏. 所有具体的交互都通过SecurityManager进行控制,它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理</li>
<li><code>Authenticator</code> : 认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现. 其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了</li>
<li><code>Authrizer</code> : 授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作,即控制着用户能访问应用中的哪些功能</li>
<li><code>Realm</code> : 可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体. 可以是JDBC实现,也可以是LDAP实现,或者内存实现等,由用户提供. 注意 : Shiro不知道你的用户 / 权限存储在哪及以何种格式存储,所以我们一般在应用中都需要实现自己的Realm</li>
<li><code>SessionManager</code> : 如果写过Servlet就应该知道Session的概念,Session需要有人去管理它的生命周期,这个组件就是SessionManager,而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境. 所以Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据. 这样的话,比如我们在Web环境用,刚开始是一台Web服务器,接着又上了台EJB服务器,这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器)</li>
<li><code>SessionDAO</code> : DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的 SessionDAO,通过如JDBC写到数据库. 比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO. 另外SessionDAO中可以使用Cache进行缓存,以提高性能</li>
<li><code>CacheManager</code> : 缓存控制器,来管理如用户、角色、权限等的缓存的. 因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能</li>
<li><code>Cryptography</code> : 密码模块,Shiro提高了一些常见的加密组件用于如密码加密 / 解密</li>
</ul>
<h3 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h3><h4 id="第一个Shiro程序"><a href="#第一个Shiro程序" class="headerlink" title="第一个Shiro程序"></a>第一个Shiro程序</h4><p><em>接下来通过一个简单的用户身份验证程序,来感受一下Shiro的魅力吧 !</em></p>
<ol>
<li><p><em>pom.xml : Maven依赖</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>4.11<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Shiro核心包 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.shiro<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>shiro-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.3.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- slf4j的接口实现 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.slf4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>slf4j-log4j12<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.7.12<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span></code></pre></div>
</li>
<li><p><em>log4j.properties : 日志配置信息</em></p>
<div class="hljs"><pre><code class="hljs t">log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=TRACE
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN</code></pre></div>
</li>
<li><p><em>shiro.ini : 存储用户身份信息(账户=密码)</em></p>
<div class="hljs"><pre><code class="hljs ini"><span class="hljs-section">[users]</span>
<span class="hljs-attr">root</span>=yubuntu0109</code></pre></div>
</li>
<li><p><em>ShiroTest.java : 验证用户登录信息</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui;

<span class="hljs-keyword">import</span> org.apache.shiro.SecurityUtils;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.IncorrectCredentialsException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.UnknownAccountException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.UsernamePasswordToken;
<span class="hljs-keyword">import</span> org.apache.shiro.config.IniSecurityManagerFactory;
<span class="hljs-keyword">import</span> org.apache.shiro.mgt.SecurityManager;
<span class="hljs-keyword">import</span> org.apache.shiro.subject.Subject;
<span class="hljs-keyword">import</span> org.apache.shiro.util.Factory;
<span class="hljs-keyword">import</span> org.junit.Test;

<span class="hljs-comment">/**
 * Shiro认证测试:验证用户登录信息
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ShiroTest</span> </span>&#123;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testLogin</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-comment">//1:加载配置文件,创建SecurityManager工厂对象</span>
        Factory&lt;SecurityManager&gt; factory = <span class="hljs-keyword">new</span> IniSecurityManagerFactory(<span class="hljs-string">"classpath:shiro.ini"</span>);
        <span class="hljs-comment">//2:获得securityManager实例对象</span>
        SecurityManager securityManager = factory.getInstance();
        <span class="hljs-comment">//3:将securityManger实例绑定到当前运行环境中,便于访问</span>
        SecurityUtils.setSecurityManager(securityManager);
        <span class="hljs-comment">//4:创建当前登录的主体</span>
        Subject currentUser = SecurityUtils.getSubject();
        <span class="hljs-comment">//5:绑定主体登录的身份/凭证,既账户及密码</span>
        UsernamePasswordToken token = <span class="hljs-keyword">new</span> UsernamePasswordToken(<span class="hljs-string">"root"</span>, <span class="hljs-string">"yubuntu0109"</span>);
        <span class="hljs-comment">//6:主体登录</span>
        <span class="hljs-keyword">try</span> &#123;
            currentUser.login(token);
            System.out.println(<span class="hljs-string">"用户身份是否验证成功 :"</span> + currentUser.isAuthenticated());
        &#125; <span class="hljs-keyword">catch</span> (UnknownAccountException e) &#123;
            System.err.println(<span class="hljs-string">"账户信息错误 !"</span>);
        &#125; <span class="hljs-keyword">catch</span> (IncorrectCredentialsException e) &#123;
            System.err.println(<span class="hljs-string">"密码信息错误 !"</span>);
        &#125; <span class="hljs-keyword">catch</span> (AuthenticationException e) &#123;
            e.printStackTrace();
        &#125;
        <span class="hljs-comment">//8:注销登录</span>
        currentUser.logout();
        System.out.println(<span class="hljs-string">"身份身份是否注销成功 :"</span> + !currentUser.isAuthenticated());

    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果如下所示 :</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">// ·····</span>
用户身份是否验证成功 :<span class="hljs-keyword">true</span>
<span class="hljs-comment">// ·····</span>
身份身份是否注销成功 :<span class="hljs-keyword">true</span></code></pre></div>


</li>
</ol>
<h4 id="官方入门案例"><a href="#官方入门案例" class="headerlink" title="官方入门案例"></a>官方入门案例</h4><ol>
<li><p><em>pom.xml : Maven依赖(同上)</em></p>
</li>
<li><p><em>log4.properties : 日志配置信息(同上)</em></p>
</li>
<li><p><em>shiro.ini : 存储具有指定权限的,不同身份的用户信息</em></p>
<div class="hljs"><pre><code class="hljs ini"><span class="hljs-comment"># =============================================================================</span>
<span class="hljs-comment"># Quickstart INI Realm configuration</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># For those that might not understand the references in this file, the</span>
<span class="hljs-comment"># definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)</span>
<span class="hljs-comment"># =============================================================================</span>

<span class="hljs-comment"># -----------------------------------------------------------------------------</span>
<span class="hljs-comment"># Users and their assigned roles</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># Each line conforms to the format defined in the</span>
<span class="hljs-comment"># org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc</span>
<span class="hljs-comment"># -----------------------------------------------------------------------------</span>
<span class="hljs-section">[users]</span>
<span class="hljs-comment"># user 'root' with password 'secret' and the 'admin' role</span>
<span class="hljs-attr">root</span> = secret, admin
<span class="hljs-comment"># user 'guest' with the password 'guest' and the 'guest' role</span>
<span class="hljs-attr">guest</span> = guest, guest
<span class="hljs-comment"># user 'presidentskroob' with password '12345' ("That's the same combination on</span>
<span class="hljs-comment"># my luggage!!!" ;)), and role 'president'</span>
<span class="hljs-attr">presidentskroob</span> = <span class="hljs-number">12345</span>, president
<span class="hljs-comment"># user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'</span>
<span class="hljs-attr">darkhelmet</span> = ludicrousspeed, darklord, schwartz
<span class="hljs-comment"># user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'</span>
<span class="hljs-attr">lonestarr</span> = vespa, goodguy, schwartz

<span class="hljs-comment"># -----------------------------------------------------------------------------</span>
<span class="hljs-comment"># Roles with assigned permissions</span>
<span class="hljs-comment"># </span>
<span class="hljs-comment"># Each line conforms to the format defined in the</span>
<span class="hljs-comment"># org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc</span>
<span class="hljs-comment"># -----------------------------------------------------------------------------</span>
<span class="hljs-section">[roles]</span>
<span class="hljs-comment"># 'admin' role has all permissions, indicated by the wildcard '*'</span>
<span class="hljs-attr">admin</span> = *
<span class="hljs-comment"># The 'schwartz' role can do anything (*) with any lightsaber:</span>
<span class="hljs-attr">schwartz</span> = lightsaber:*
<span class="hljs-comment"># The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with</span>
<span class="hljs-comment"># license plate 'eagle5' (instance specific id)</span>
<span class="hljs-attr">goodguy</span> = winnebago:drive:eagle5</code></pre></div>
</li>
<li><p><em>Quickstart.java : 一个简单的入门级程序,教你如何使用Shiro的API</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui;

<span class="hljs-keyword">import</span> org.apache.shiro.SecurityUtils;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.*;
<span class="hljs-keyword">import</span> org.apache.shiro.config.IniSecurityManagerFactory;
<span class="hljs-keyword">import</span> org.apache.shiro.mgt.SecurityManager;
<span class="hljs-keyword">import</span> org.apache.shiro.session.Session;
<span class="hljs-keyword">import</span> org.apache.shiro.subject.Subject;
<span class="hljs-keyword">import</span> org.apache.shiro.util.Factory;
<span class="hljs-keyword">import</span> org.slf4j.Logger;
<span class="hljs-keyword">import</span> org.slf4j.LoggerFactory;

<span class="hljs-comment">/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * <span class="hljs-doctag">@since</span> 0.9 RC2
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Quickstart</span> </span>&#123;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">transient</span> Logger log = LoggerFactory.getLogger(Quickstart<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;

        <span class="hljs-comment">// The easiest way to create a Shiro SecurityManager with configured</span>
        <span class="hljs-comment">// realms, users, roles and permissions is to use the simple INI config.</span>
        <span class="hljs-comment">// We'll do that by using a factory that can ingest a .ini file and</span>
        <span class="hljs-comment">// return a SecurityManager instance:</span>

        <span class="hljs-comment">// Use the shiro.ini file at the root of the classpath</span>
        <span class="hljs-comment">// (file: and url: prefixes load from files and urls respectively):</span>
        Factory&lt;SecurityManager&gt; factory = <span class="hljs-keyword">new</span> IniSecurityManagerFactory(<span class="hljs-string">"classpath:shiro.ini"</span>);
        SecurityManager securityManager = factory.getInstance();

        <span class="hljs-comment">// for this simple example quickstart, make the SecurityManager</span>
        <span class="hljs-comment">// accessible as a JVM singleton.  Most applications wouldn't do this</span>
        <span class="hljs-comment">// and instead rely on their container configuration or web.xml for</span>
        <span class="hljs-comment">// webapps.  That is outside the scope of this simple quickstart, so</span>
        <span class="hljs-comment">// we'll just do the bare minimum so you can continue to get a feel</span>
        <span class="hljs-comment">// for things.</span>
        SecurityUtils.setSecurityManager(securityManager);

        <span class="hljs-comment">// Now that a simple Shiro environment is set up, let's see what you can do:</span>

        <span class="hljs-comment">// get the currently executing user:</span>
        Subject currentUser = SecurityUtils.getSubject();

        <span class="hljs-comment">// Do some stuff with a Session (no need for a web or EJB container!!!)</span>
        Session session = currentUser.getSession();
        session.setAttribute(<span class="hljs-string">"someKey"</span>, <span class="hljs-string">"aValue"</span>);
        String value = (String) session.getAttribute(<span class="hljs-string">"someKey"</span>);
        <span class="hljs-keyword">if</span> (value.equals(<span class="hljs-string">"aValue"</span>)) &#123;
            log.info(<span class="hljs-string">"Retrieved the correct value! ["</span> + value + <span class="hljs-string">"]"</span>);
        &#125;

        <span class="hljs-comment">// let's login the current user so we can check against roles and permissions:</span>
        <span class="hljs-keyword">if</span> (!currentUser.isAuthenticated()) &#123;
            UsernamePasswordToken token = <span class="hljs-keyword">new</span> UsernamePasswordToken(<span class="hljs-string">"lonestarr"</span>, <span class="hljs-string">"vespa"</span>);
            token.setRememberMe(<span class="hljs-keyword">true</span>);
            <span class="hljs-keyword">try</span> &#123;
                currentUser.login(token);
            &#125; <span class="hljs-keyword">catch</span> (UnknownAccountException uae) &#123;
                log.info(<span class="hljs-string">"There is no user with username of "</span> + token.getPrincipal());
            &#125; <span class="hljs-keyword">catch</span> (IncorrectCredentialsException ice) &#123;
                log.info(<span class="hljs-string">"Password for account "</span> + token.getPrincipal() + <span class="hljs-string">" was incorrect!"</span>);
            &#125; <span class="hljs-keyword">catch</span> (LockedAccountException lae) &#123;
                log.info(<span class="hljs-string">"The account for username "</span> + token.getPrincipal() + <span class="hljs-string">" is locked.  "</span> +
                        <span class="hljs-string">"Please contact your administrator to unlock it."</span>);
            &#125;
            <span class="hljs-comment">// ... catch more exceptions here (maybe custom ones specific to your application?</span>
            <span class="hljs-keyword">catch</span> (AuthenticationException ae) &#123;
                <span class="hljs-comment">//unexpected condition?  error?</span>
            &#125;
        &#125;

        <span class="hljs-comment">//say who they are:</span>
        <span class="hljs-comment">//print their identifying principal (in this case, a username):</span>
        log.info(<span class="hljs-string">"User ["</span> + currentUser.getPrincipal() + <span class="hljs-string">"] logged in successfully."</span>);

        <span class="hljs-comment">//test a role:</span>
        <span class="hljs-keyword">if</span> (currentUser.hasRole(<span class="hljs-string">"schwartz"</span>)) &#123;
            log.info(<span class="hljs-string">"May the Schwartz be with you!"</span>);
        &#125; <span class="hljs-keyword">else</span> &#123;
            log.info(<span class="hljs-string">"Hello, mere mortal."</span>);
        &#125;

        <span class="hljs-comment">//test a typed permission (not instance-level)</span>
        <span class="hljs-keyword">if</span> (currentUser.isPermitted(<span class="hljs-string">"lightsaber:wield"</span>)) &#123;
            log.info(<span class="hljs-string">"You may use a lightsaber ring.  Use it wisely."</span>);
        &#125; <span class="hljs-keyword">else</span> &#123;
            log.info(<span class="hljs-string">"Sorry, lightsaber rings are for schwartz masters only."</span>);
        &#125;

        <span class="hljs-comment">//a (very powerful) Instance Level permission:</span>
        <span class="hljs-keyword">if</span> (currentUser.isPermitted(<span class="hljs-string">"winnebago:drive:eagle5"</span>)) &#123;
            log.info(<span class="hljs-string">"You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "</span> +
                    <span class="hljs-string">"Here are the keys - have fun!"</span>);
        &#125; <span class="hljs-keyword">else</span> &#123;
            log.info(<span class="hljs-string">"Sorry, you aren't allowed to drive the 'eagle5' winnebago!"</span>);
        &#125;

        <span class="hljs-comment">//all done - log out!</span>
        currentUser.logout();

        System.exit(<span class="hljs-number">0</span>);
    &#125;
&#125;</code></pre></div></li>
</ol>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Java/">Java</a>
                    
                      <a class="hover-with-bg" href="/tags/Shiro/">Shiro</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/08/01/%E8%AF%A6%E8%A7%A3Shiro%E7%99%BB%E5%BD%95%E7%99%BB%E5%87%BA%E7%9A%84%E6%93%8D%E4%BD%9C%E6%B5%81%E7%A8%8B/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">详解Shiro登录登出的操作流程</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/07/29/How-to-create-a-pull-request-from-a-fork/">
                        <span class="hidden-mobile">How to create a pull request from a fork</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Hi Shiro ~&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
